#!/usr/bin/env python3
"""
EndoSight-UC 系统测试脚本
测试前后端连接和基本功能
"""

import requests
import json
import time
import sys

# 配置
BASE_URL = "http://localhost:8107"
API_BASE = f"{BASE_URL}/api"

def print_test_header(test_name):
    """打印测试标题"""
    print(f"\n{'='*60}")
    print(f"🧪 测试: {test_name}")
    print(f"{'='*60}")

def print_success(message):
    """打印成功消息"""
    print(f"✅ {message}")

def print_error(message):
    """打印错误消息"""
    print(f"❌ {message}")

def print_info(message):
    """打印信息"""
    print(f"ℹ️  {message}")

def test_frontend_connection():
    """测试前端连接"""
    print_test_header("前端服务连接测试")

    try:
        response = requests.get(BASE_URL, timeout=5)
        if response.status_code == 200:
            print_success("前端服务连接正常")
            print_info(f"响应状态码: {response.status_code}")
            return True
        else:
            print_error(f"前端服务响应异常: {response.status_code}")
            return False
    except Exception as e:
        print_error(f"前端服务连接失败: {str(e)}")
        return False

def test_api_connection():
    """测试API连接"""
    print_test_header("后端API连接测试")

    try:
        response = requests.get(f"{API_BASE}/test", timeout=5)
        if response.status_code == 200:
            data = response.json()
            if data.get('success'):
                print_success("后端API连接正常")
                print_info(f"响应消息: {data.get('message')}")
                return True
            else:
                print_error("API响应格式异常")
                return False
        else:
            print_error(f"API响应异常: {response.status_code}")
            return False
    except Exception as e:
        print_error(f"API连接失败: {str(e)}")
        return False

def test_login():
    """测试登录功能"""
    print_test_header("用户登录功能测试")

    login_data = {
        "username": "admin",
        "password": "admin123"
    }

    try:
        response = requests.post(f"{API_BASE}/auth/login",
                               json=login_data,
                               timeout=5)
        if response.status_code == 200:
            data = response.json()
            if data.get('success'):
                token = data.get('data', {}).get('token')
                doctor = data.get('data', {}).get('doctor')

                print_success("登录功能正常")
                print_info(f"用户名: {doctor.get('username') if doctor else 'N/A'}")
                print_info(f"真实姓名: {doctor.get('real_name') if doctor else 'N/A'}")
                print_info(f"角色ID: {doctor.get('role') if doctor else 'N/A'}")
                print_info(f"Token长度: {len(token) if token else 0}")

                return token
            else:
                print_error(f"登录失败: {data.get('message')}")
                return None
        else:
            print_error(f"登录请求失败: {response.status_code}")
            return None
    except Exception as e:
        print_error(f"登录请求异常: {str(e)}")
        return None

def test_protected_api(token):
    """测试需要认证的API"""
    print_test_header("认证API访问测试")

    if not token:
        print_error("缺少认证令牌，跳过测试")
        return False

    headers = {
        'Authorization': f'Bearer {token}'
    }

    try:
        # 测试获取评分任务
        response = requests.get(f"{API_BASE}/scoring/tasks",
                              headers=headers,
                              timeout=5)

        if response.status_code == 200:
            data = response.json()
            if data.get('success'):
                print_success("认证API访问正常")
                print_info(f"任务数量: {data.get('total', 0)}")
                return True
            else:
                print_error(f"API响应异常: {data.get('message')}")
                return False
        else:
            print_error(f"API访问失败: {response.status_code}")
            return False

    except Exception as e:
        print_error(f"认证API访问异常: {str(e)}")
        return False

def test_health_check():
    """测试健康检查"""
    print_test_header("系统健康检查")

    try:
        response = requests.get(f"{API_BASE}/health", timeout=5)
        if response.status_code == 200:
            data = response.json()
            if data.get('success'):
                print_success("系统健康状态正常")

                services = data.get('services', {})
                for service, status in services.items():
                    status_icon = "🟢" if status == "healthy" else "🔴"
                    print_info(f"{status_icon} {service}: {status}")

                return True
            else:
                print_error("健康检查响应异常")
                return False
        else:
            print_error(f"健康检查失败: {response.status_code}")
            return False
    except Exception as e:
        print_error(f"健康检查异常: {str(e)}")
        return False

def main():
    """主测试函数"""
    print("🚀 EndoSight-UC 系统测试开始")
    print(f"📍 测试目标: {BASE_URL}")

    results = []

    # 执行测试
    results.append(("前端服务连接", test_frontend_connection()))
    results.append(("后端API连接", test_api_connection()))
    results.append(("系统健康检查", test_health_check()))

    token = test_login()
    results.append(("用户登录功能", bool(token)))

    if token:
        results.append(("认证API访问", test_protected_api(token)))

    # 测试结果统计
    print_test_header("测试结果汇总")

    passed = sum(1 for _, result in results if result)
    total = len(results)

    for test_name, result in results:
        status = "✅ 通过" if result else "❌ 失败"
        print(f"{test_name:20} : {status}")

    print(f"\n📊 总体结果: {passed}/{total} 项测试通过")

    if passed == total:
        print_success("🎉 所有测试通过！系统运行正常！")
        print_info(f"📱 前端地址: {BASE_URL}")
        print_info(f"🔑 测试账户: admin / admin123")
        return 0
    else:
        print_error("⚠️  部分测试失败，请检查相关服务")
        return 1

if __name__ == "__main__":
    try:
        exit_code = main()
        sys.exit(exit_code)
    except KeyboardInterrupt:
        print("\n\n⚠️  测试被用户中断")
        sys.exit(1)
    except Exception as e:
        print(f"\n\n💥 测试过程中发生异常: {str(e)}")
        sys.exit(1)